package com.example.myblog.controller;

import com.example.myblog.model.Category;
import com.example.myblog.service.CategoryService;
import com.example.myblog.service.SettingsService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;

import java.util.List;

/**
 * 全局控制器增强
 * 主要用于向所有视图的Model中添加公共数据
 */
@ControllerAdvice
public class GlobalControllerAdvice {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SettingsService settingsService;

    /**
     * 向所有模型添加分类列表
     * @return categories
     */
    @ModelAttribute("categories")
    public List<Category> getCategories() {
        return categoryService.getAllCategories();
    }

    /**
     * 向所有模型添加网站名称
     * @return siteName
     */
    @ModelAttribute("siteName")
    public String getSiteName() {
        return settingsService.getSettingValueByKey("site_name", "咋还没来");
    }

    /**
     * [问题修复关键]
     * 向所有模型中添加当前请求的URI
     * @param request HTTP请求
     * @return requestURI
     */
    @ModelAttribute("requestURI")
    public String getRequestURI(HttpServletRequest request) {
        return request.getRequestURI();
    }
}